package com.cn.aam.checaiduo.center;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.BuildConfig;
import com.cn.aam.checaiduo.bean.UserB;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import static android.content.Context.MODE_PRIVATE;


/**
 * 用户管理中心
 */
public class UserCenter {

    //单例模式
    private volatile static UserCenter INSTANCE;//声明 volatiel 禁止指令重排序优化

    private static final String USER_PERSONAL_SHAREPRE = "user_personal_sharepre";

    private UserCenter() {
    }

    public static UserCenter getInstance() {
        return UserCenter.Holder.INSTANCE;
    }

    private static class Holder {
        static UserCenter INSTANCE = new UserCenter();

    }

    /**
     * Personal Info SharePrefrences - 用于存放用服务器返回的用户信息 @ UserM.java
     */
    public void clearUserM() {
        SharedPreferences sp = AppData.getContext().getSharedPreferences(BuildConfig.APPNAME, MODE_PRIVATE);
        sp.edit().remove(USER_PERSONAL_SHAREPRE).apply();
    }

    public void setUser(UserB info) {
        SharedPreferences sp = AppData.getContext().getSharedPreferences(BuildConfig.APPNAME, MODE_PRIVATE);
        sp.edit().putString(USER_PERSONAL_SHAREPRE, info.toJson()).apply();
    }


    public UserB getUser() {
        SharedPreferences sp = AppData.getContext().getSharedPreferences(BuildConfig.APPNAME, MODE_PRIVATE);
        String infoString = sp.getString(USER_PERSONAL_SHAREPRE, "");
        if (TextUtils.isEmpty(infoString)) {

            return null;
        }

        return new Gson().fromJson(infoString, UserB.class);
    }


    /**
     * 注销
     */
    public void logOut() {
//        WMToast.normal("已退出登录");
        clearUserM();
        MobclickAgent.onProfileSignOff();
        SharePreferenceCenter.getInstance().clearFinanceData();
        AppData.closeActivityExceptMain();
    }


    /**
     * 用户是否登录
     */
    public boolean isUserLogin() {
        return getUser() != null;
    }


}
